﻿using Lonewolf.Entity;
using Lonewolf.Infrastructure;
using Lonewolf.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lonewolf.Service
{
    public partial class MenuInfoService : BaseService<MenuInfo>, IMenuInfoService
    {
        private IAdminRoleService adminRole;
        private IRoleMenuService roleMenu;
        private List<MenuNavBar> menuNavBars = new List<MenuNavBar>();
        MenuNavBar curItem = new MenuNavBar();
        public MenuInfoService(EFDbContext dbContext, IAdminRoleService adminRole, IRoleMenuService roleMenu) : base(dbContext)
        {
            this.adminRole = adminRole;
            this.roleMenu = roleMenu;
        }
        public IQueryable<MenuInfo> GetMenuListByUserId(string userId)
        {
            //根据用户id获取角色集合
            var roleIds = adminRole.GetRoleIdsByUserId(userId);
            //根据角色ID查询菜单信息
            var menuIds = roleMenu.GetMenusByRoleId(roleIds);
            //根据得到的权限（菜单）Id查询所有菜单
            return QueryNoTracking().Where(a => menuIds.Contains(a.Id) && a.MenuIsUse == true);
        }
        public JsonResult<TopMenuEntity> GetTopMenuList(string userId)
        {
            DateTime startTime = DateTime.Now;
            var result = new JsonResult<TopMenuEntity>();
            result.data = new List<TopMenuEntity>();
            if (userId.IsNullOrEmpty())
                return result;
            try
            {
                var menuList = GetMenuListByUserId(userId);
                //开始循环取菜单
                foreach (var item in menuList.Where(a => a.MenuType == MenuType.Mod && a.MenuLevel == 1 && a.MenuHierarchy == 1).OrderBy(b => b.MenuSort))
                {
                    TopMenuEntity topMenu = new TopMenuEntity()
                    {
                        title = item.MenuName,
                        icon = item.MenuIcon,
                        id = item.Id
                    };
                    result.data.Add(topMenu);
                }
                result.success = true;
                result.message = Result.GetSuccess();
                result.count = result.data.Count;
            }
            catch (Exception ex)
            {
                result.code = 500;
                result.success = false;
                result.message = ex.Message;
            }

            DateTime endTime = DateTime.Now;
            TimeSpan ts = endTime.Subtract(startTime);
            result.time = ts.TotalMilliseconds.ToString() + "ms";
            return result;
        }
        public List<MenuNavBar> GetChildren(List<MenuInfo> child, string Id)
        {
            List<MenuNavBar> navBars = new List<MenuNavBar>();
            var list = child.Where(a => a.SuperiorId == Id);
            foreach (var item in list)
            {
                MenuNavBar navBar = new MenuNavBar();
                navBar.icon = item.MenuIcon;
                navBar.id = item.Id;
                navBar.title = item.MenuName;
                navBar.url = item.MenuUrl;
                navBars.Add(navBar);
            }
            return navBars;
        }
        public void LoopToAppendChildren(List<MenuInfo> child, MenuNavBar curItem)
        {
            var subItems = GetChildren(child, curItem.id);
            curItem.children = new List<MenuNavBar>();
            curItem.children.AddRange(subItems);
            foreach (var subItem in subItems)
            {
                LoopToAppendChildren(child, subItem);
            }
        }
        public JsonResult<MenuNavBar> GetLeftMenus(string userId, string Id)
        {
            DateTime startTime = DateTime.Now;
            var result = new JsonResult<MenuNavBar>();
            result.data = new List<MenuNavBar>();
            if (userId.IsNullOrEmpty() || Id.IsNullOrEmpty())
                return result;
            try
            {
                //1、读取此用户所有菜单
                var menuList = GetMenuListByUserId(userId).ToList();
                //2、读取上级ID为传入ID的菜单列表，在左侧显示为一级菜单
                //3、读取上级ID为2中这些菜单ID的列表
                //4、整合整个列表输出
                var list = menuList.Where(a => a.MenuLevel == 2 && a.SuperiorId == Id && a.MenuType == MenuType.Menu).ToList();
                foreach (var item in list)
                {
                    MenuNavBar bar = new MenuNavBar()
                    {
                        icon = item.MenuIcon,
                        id = item.Id,
                        title = item.MenuName,
                        url = null
                    };
                    LoopToAppendChildren(menuList, bar);
                    result.data.Add(bar);
                }
                result.success = true;
                result.message = Result.GetSuccess();
                result.count = result.data.Count;
            }
            catch (Exception ex)
            {
                result.code = 500;
                result.success = false;
                result.message = ex.Message;
            }
            DateTime endTime = DateTime.Now;
            TimeSpan ts = endTime.Subtract(startTime);
            result.time = ts.TotalMilliseconds.ToString() + "ms";
            return result;
        }

        public JsonResult<MenuInfo> GetButtonByUrl(string userId, string url)
        {
            var result = new JsonResult<MenuInfo>();
            result.data = new List<MenuInfo>();
            if (userId.IsNullOrEmpty() || url.IsNullOrEmpty())
            {
                result.message = "缺少必要参数，数据获取失败！";
                return result;
            }
            try
            {
                var sup = GetMenuListByUserId(userId).FirstOrDefault(a => a.MenuUrl == url);
                var list = GetMenuListByUserId(userId).Where(a => a.SuperiorId == sup.Id && a.MenuType == MenuType.Button).OrderBy(c => c.MenuSort);
                foreach (var item in list)
                {
                    MenuInfo menu = new MenuInfo()
                    {
                        Id = item.Id,
                        MenuEvent = item.MenuEvent,
                        MenuUrl = item.MenuUrl,
                        MenuName = item.MenuName,
                        MenuIcon = item.MenuIcon,
                        MenuSort = item.MenuSort,
                        LayerWidth=item.LayerWidth,
                        LayerHeight=item.LayerHeight
                    };
                    result.data.Add(menu);
                }
                result.success = true;
                result.message = "获取数据成功！";
            }
            catch (Exception ex)
            {

                result.code = 500;
                result.message = ex.Message;
            }
            return result;
        }

        public List<TreeSelect> GetModularByUserId(string userId)
        {
            var list = GetMenuListByUserId(userId);
            var treeList = new List<TreeSelect>();
            foreach (var item in list)
            {
                TreeSelect model = new TreeSelect();
                model.id = item.Id;
                model.text = item.MenuName;
                model.parentId = item.SuperiorId;
                model.level = item.MenuLevel;
                treeList.Add(model);
            }
            return treeList;
        }

        public async Task<JsonResult<string>> SaveAsync(MenuInfo model,string userId)
        {
            var result =new JsonResult<string>();
            if(model==null)
            {
                result.message = "修改数据不能为空！";
                return result;
            }
            else
            {
                try
                {
                    if (model.Id.IsNullOrEmpty())
                    {
                        if (model.SuperiorId == null || model.SuperiorId == "")
                            model.SuperiorId = "a-1";
                        var supModel = QueryNoTracking().FirstOrDefault(a => a.Id == model.SuperiorId);
                        model.MenuLevel = supModel == null ? 0 : supModel.MenuLevel + 1;
                        model.MenuIsUse = model.MenuIsUse == null ? false : true;
                        model.CreateUser = userId;
                        await InsertAsync(model);
                    }
                    else
                    {
                        if (model.SuperiorId == null || model.SuperiorId == "")
                            model.SuperiorId = "a-1";
                        var supModel = QueryNoTracking().FirstOrDefault(a => a.Id == model.SuperiorId);
                        model.MenuLevel = supModel == null ? 0 : supModel.MenuLevel + 1;
                        model.MenuIsUse = model.MenuIsUse == null ? false : true;
                        model.LastChangeTime = DateTime.Now;
                        Update(model);
                    }
                    var flag = await SaveChangesAsync();
                    result.success = flag;
                    result.message = flag ? Result.Success() : Result.Error();
                }
                catch (Exception ex)
                {
                    result.code = 500;
                    result.message = ex.Message;
                }
            }
            return result;
                    
        }

        public async Task<JsonResult<Page<MenuInfo>>> GetPagesAsync(int PageIndex, int PageSize)
        {
            var result = new JsonResult<Page<MenuInfo>>();
            try
            {
                var list = await QueryNoTracking().ToPageAsync(PageIndex, PageSize);
                if (list.Items==null||list.Items.Count==0)
                {
                    result.message = "暂无数据！";
                    return result;
                }
                result.success = true;
                result.message = "获取数据成功！";
                //转换数据
                result.Entity = list.ToViewPage(p=>new MenuInfo {
                    MenuLevel=p.MenuLevel,
                    MenuName=p.MenuName,
                    MenuIcon=p.MenuIcon,
                    MenuIsUse=p.MenuIsUse,
                    MenuType=p.MenuType,
                    MenuSort=p.MenuSort,
                    SuperiorId=p.SuperiorId,
                    Id=p.Id
                });
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.code = 500; 
            }
            return result;
        }
    }
}
